package com.dq.health.security;

import com.dq.health.dto.response.menu.SysMenuTreeInfo;
import com.dq.health.entity.menu.SysMenu;
import com.dq.health.entity.user.UserBaseInfo;
import com.dq.health.service.IAPIMenuService;
import com.dq.health.service.IAPIUserService;
import com.dq.health.utils.data.Tree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailService implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailService.class);

    private @Autowired IAPIUserService sysUserService;

    private @Autowired IAPIMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String loginName) {

        logger.info("获取{}用户信息", loginName);

        UserBaseInfo userBaseInfo = sysUserService.queryUserByUserName(loginName);
        if (userBaseInfo == null) {
            userBaseInfo = sysUserService.queryUserByMobile(loginName);
        }

        if (userBaseInfo == null) {
            throw new UsernameNotFoundException(loginName + " not found");
        }

        if (userBaseInfo.getUserStatus() != 1) {
            throw new DisabledException(String.format("账号%s已经停用", loginName));
        }

        // TODO 登陆错误次数锁定
        // SysUserLoginFail loginFail = sysUserLoginFailService.getByUserId(userId);
        // if (loginFail != null) {
        // Integer status = loginFail.getStatus();
        // if (status.intValue() == 1) {
        // throw new LockedException(String.format("账号%s已经锁定", loginName));
        // }
        // }

        UserDetailsModel retModel = new UserDetailsModel();
        retModel.setSysUser(userBaseInfo);

        // 权限菜单
        Long roleId = userBaseInfo.getRoleId();
        List<SysMenu> sysMenus = menuService.selectMenuListByRoleId(roleId);
        Tree<SysMenuTreeInfo> sysMenuTreeInfoTree = menuService.buildMenus(sysMenus);
        retModel.setMenuTreeInfos(sysMenuTreeInfoTree);

        return retModel;
    }

}
